package com.xiaohai.wx.weather.web;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import com.xiaohai.wx.weather.dto.messageOut.TextMessage;
import com.xiaohai.wx.weather.message.GeneralMsgHandler;
import com.xiaohai.wx.weather.util.MessageUtil;
import com.xiaohai.wx.weather.util.SpringContextUtil;

@WebServlet(asyncSupported = false, name = "WeixinAPI", urlPatterns = { "/weixinservlet" })
public class WeixinServlet extends HttpServlet {

	private static final long serialVersionUID = -2776902810130266533L;

	private static Logger logger = Logger.getLogger(WeixinServlet.class
			.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		logger.info(signature + " : " + timestamp + " : " + nonce + " : "
				+ echostr);

		PrintWriter out = resp.getWriter();
		out.write(echostr);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String respContent = "对不起，系统维护中...";

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
		} catch (Exception e) {
			logger.error("Exception to set character encoding: " + e);
			respContent = "Sorry. We're working on some server problems. Please wait...";
		}

		GeneralMsgHandler generalHandler = (GeneralMsgHandler) SpringContextUtil
				.getBean("GeneralMsgHandler");

		Map<String, String> requestMap = null;
		try {
			requestMap = MessageUtil.parseXml(request);
		} catch (DocumentException e) {
			logger.error("Parse Income XML error: " + e);
			throw new IOException("Parse Request XML ERROR!");
		} catch (IOException e) {
			logger.error("Parse Income XML error: " + e);
			throw new IOException("Parse Request XML ERROR!");
		}

		String user_OpenId = requestMap.get("FromUserName");
		String server_OpenId = requestMap.get("ToUserName");

		try {
			respContent = generalHandler.handleMsg(requestMap);
		} catch (Exception e) {
			logger.error("Exception when handle msg: " + e);
			e.printStackTrace();
		}

		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(user_OpenId);
		textMessage.setFromUserName(server_OpenId);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);

		textMessage.setContent(respContent);
		String respMessage = MessageUtil.textMessageToXml(textMessage);

		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}
}
